'use strict';

// running：监控状态
chrome.storage.local.get({
  running: 0, currPageId: -1,
  cpu: "", gpu: "", upload: false
}, function (item) {
  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, (tabs) => {
    let bRunning = item.running === 1;  // 是否监控中
    let bCurrPage = tabs[0].id === item.currPageId; // 监控页面是否为当前页面

    document.getElementsByName('cpu')[0].value = item.cpu;
    document.getElementsByName('gpu')[0].value = item.gpu;
    document.getElementsByName('upload')[0].checked = item.upload;

    document.getElementById('start').style.display = !bRunning ? 'block' : 'none';
    document.getElementById('stop').style.display = bRunning & bCurrPage ? 'block' : 'none';
    document.getElementById('info').style.display = bRunning & !bCurrPage ? 'block' : 'none';
  })
});

// 点击“开始”
document.getElementById('start').addEventListener('click', function () {
  chrome.storage.local.set({ running: 1 }, function () {
    document.getElementById('start').style.display = 'none';
    document.getElementById('stop').style.display = 'block';
  });

  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, (tabs) => {
    chrome.storage.local.set({ currPageId: tabs[0].id });
    chrome.tabs.sendMessage(tabs[0].id, { type: 'START' }, function (_) {
      window.open('./view.html');
    })
  })
})

// 停止监控
function stopRecord() {
  chrome.storage.local.set({ running: 0 }, function () {
    document.getElementById('start').style.display = 'block';
    document.getElementById('stop').style.display = 'none';
    document.getElementById('info').style.display = 'none';
  });

  chrome.tabs.query({
    active: true,
    currentWindow: true
  }, (tabs) => {
    chrome.storage.local.set({ currPageId: -1 });
    chrome.tabs.sendMessage(tabs[0].id, { type: 'STOP' })
  })
}

// 点击“停止”
document.getElementById('stop').addEventListener('click', function () {
  stopRecord();
})
document.getElementById('link-stop').addEventListener('click', function () {
  stopRecord();
})

// 监控参数的更改
document.getElementsByName('cpu')[0].addEventListener('change', function () {
  chrome.storage.local.set({ cpu: this.value })
});
document.getElementsByName('gpu')[0].addEventListener('change', function () {
  chrome.storage.local.set({ gpu: this.value })
});
document.getElementsByName('upload')[0].addEventListener('change', function () {
  chrome.storage.local.set({ upload: this.checked })
});